package com.yiwise.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import java.nio.charset.Charset;
import java.util.List;

@Configuration
@EnableWebMvc
public class CommonMvcConfig implements WebMvcConfigurer {
    private static final Logger logger = LoggerFactory.getLogger(CommonMvcConfig.class);

    @Resource
    private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter;

    @Bean
    public MDCDecoratedServlet dispatcherServlet() {
        logger.info("==== dispatcherServlet execute ====");
        return new MDCDecoratedServlet();
    }

    @Bean
    public ServletRegistrationBean<HttpServlet> dispatcherRegistration(DispatcherServlet dispatcherServlet) {
        logger.info("==== dispatcherRegistration execute ====");

        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
        return new ServletRegistrationBean<>(dispatcherServlet);
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        logger.info("==== mappingJackson2HttpMessageConverter execute ====");

        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));

        converters.add(stringConverter);
        converters.add(mappingJackson2HttpMessageConverter);
    }
}